<template>
  <div class="userStore-container">
    <div class="store-info-container">
      <!-- 信息卡片 -->
      <el-card class="store-info-card">
        <template #header>
          <div class="card-header">
            <h3>供应商信息</h3>
          </div>
        </template>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="所属分类">
            <!-- <span>
              {{
                storeInfo.category_data &&
                storeInfo.category_data.map((item) => item.name).join('、')
              }}
            </span> -->
            <el-select
              v-model="storeInfo.category_ids"
              placeholder="请选择所属分类"
              multiple
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="所属品牌">
            <span>
              {{
                storeInfo.data &&
                storeInfo.data.map((item) => item.name).join('、')
              }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            <span>{{ storeInfo.phone }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="供应商名称">
            <el-input
              v-model="storeInfo.name"
              :class="{ 'is-error': errors.name }"
            />
          </el-descriptions-item>
          <el-descriptions-item label="详细地址">
            <div style="display: flex; align-items: center; gap: 20px">
              <span>{{ storeInfo.address }}</span>
              <div class="set-address" @click="handleSetAddress">设置地址</div>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="店铺经纬度">
            <span>{{ storeInfo.lng }},{{ storeInfo.lat }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="营业执照">
            <el-upload
              ref="uploadBusRef"
              v-model:file-list="busFilelist"
              class="upload-demo"
              :action="uploadParams['host']"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceedBus"
              :data="uploadParams['param']"
              :on-success="handleSuccessBus"
              :on-error="handleError"
              :on-preview="handlePreview('business_license')"
              :on-remove="handleRemoveBus"
              list-type="picture-card"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  上传文件大小在20M内，支持.pdf/.jpg/.png/.webp格式
                </div>
              </template>
            </el-upload>
          </el-descriptions-item>
          <el-descriptions-item label="店铺logo">
            <el-upload
              ref="uploadRef"
              v-model:file-list="logoFilelist"
              class="upload-demo"
              :action="uploadParams['host']"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed"
              :data="uploadParams['param']"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-preview="handlePreview('logo')"
              :on-remove="handleRemove"
              list-type="picture-card"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  上传文件大小在20M内，支持.pdf/.jpg/.png/.webp格式
                </div>
              </template>
            </el-upload>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <div class="button-container">
        <el-button @click="handleReturn">返回</el-button>
        <el-button
          v-permissions="['userSupplierInfoEdit']"
          v-repeat
          type="primary"
          @click="handleSubmit"
        >
          修改
        </el-button>
      </div>
    </div>
    <mapDialogComponent
      ref="mapDialogComponentRef"
      @fetch-data="handleFetchData"
    />

    <!-- 添加图片预览组件 -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="[previewUrl]"
      :hide-on-click-modal="true"
      @close="showViewer = false"
    />
  </div>
</template>

<script lang="ts">
  export default {
    name: 'userStoreInfo',
  }
</script>

<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage, genFileId } from 'element-plus'
  import { getOSSParam } from '@/api/common'
  import { getSupplierInfo, editSupplierInfo } from '@/api/supplier'
  import mapDialogComponent from './components/mapDialogComponent.vue'
  import { getcateList } from '@/api/goods'
  const router = useRouter()
  const route = useRoute()
  const action = ref(route.query.action || 'view')

  // 添加校验规则
  const rules = {
    name: { required: true, message: '请输入供应商名称' },
    phone: { required: true, message: '请输入手机号' },
    address: { required: true, message: '请设置店铺地址' },
    business_license: { required: true, message: '请上传营业执照' },
    logo: { required: true, message: '请上传店铺logo' },
  }

  // 错误状态
  const errors = reactive({
    name: false,
    phone: false,
    address: false,
    logo: false,
    business_license: false,
  })

  // 店铺信息数据
  const storeInfo: any = reactive({
    category: {},
    data: [],
    name: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    lng: '',
    lat: '',
    address: '',
    business_license: '', // 需要替换为实际的图片路径
    logo: '', // 需要替换为实际的图片路径
    category_ids: [], // 分类ids
  })

  // 返回按钮处理函数
  const handleReturn = () => {
    busFilelist.value = []
    logoFilelist.value = []
    getSupplierInfoData()
  }
  const mapDialogComponentRef = ref()

  const handleSetAddress = () => {
    mapDialogComponentRef.value.open()
  }

  const handleFetchData = (val) => {
    console.log(val)
    storeInfo.lng = val.longitude
    storeInfo.lat = val.latitude
    storeInfo.address = val.address
    storeInfo.area = val.zone[2]
    storeInfo.city = val.zone[1]
    storeInfo.province = val.zone[0]
  }
  const CheckRulesEmpty = () => {
    let isValid = true
    let firstErrorField = ''

    // 重置所有错误状态
    Object.keys(errors).forEach((key) => {
      errors[key] = false
    })

    // 检查每个必填字段
    Object.keys(rules).forEach((key) => {
      if (!storeInfo[key]) {
        errors[key] = true
        isValid = false
        if (!firstErrorField) {
          firstErrorField = rules[key].message
        }
      }
    })

    if (!isValid) {
      ElMessage.error(firstErrorField)
    }

    return isValid
  }

  const handleSubmit = () => {
    if (CheckRulesEmpty()) {
      console.log(storeInfo)
      // 这里添加提交逻辑
      editSupplierInfo({
        ...storeInfo,
        category_ids: storeInfo.category_ids.join(','),
      }).then((res: any) => {
        if (res.code === 200) {
          ElMessage.success('修改成功')
          handleReturn()
        }
      })
    }
  }

  const uploadParams: globalItem = ref({
    host: '',
    param: {},
    dir: '',
  })

  const uploadRef = ref(null)
  const uploadBusRef = ref(null)
  const image_list = ref(['image/png', 'image/jpeg', 'image/webp'])
  const uploadLoading = ref(false)
  const beforeUpload = (rawFile) => {
    if (image_list.value.includes(rawFile.type)) {
      if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('上传的图片不得大于10M!')
        return false
      }
      const image_type = rawFile.type.split('/')[1]
      uploadParams.value.param.key = `${uploadParams.value.dir}/${rawFile.uid}.${image_type}`
      uploadLoading.value = true
      return true
    } else {
      ElMessage.error('上传的图片不是图片(jpg,png,webp)类型')
      return false
    }
  }
  const handleExceed = (files) => {
    uploadRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value.handleStart(file)
    uploadRef.value.submit()
  }
  const handleExceedBus = (files) => {
    uploadBusRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadBusRef.value.handleStart(file)
    uploadBusRef.value.submit()
  }

  const handleSuccess: any = async () => {
    storeInfo.logo = `${uploadParams.value.host}/${uploadParams.value.param.key}`
    uploadLoading.value = false
  }
  const handleSuccessBus = async () => {
    storeInfo.business_license = `${uploadParams.value.host}/${uploadParams.value.param.key}`
    uploadLoading.value = false
  }

  const handleError = (err) => {
    ElMessage.error('上传简历失败, 请尝试重新上传')
    getOSSParams()
    uploadLoading.value = false
  }

  // 预览相关变量
  const showViewer = ref(false)
  const previewUrl = ref('')

  // 修改预览处理函数
  const handlePreview = (key: string) => (file: any) => {
    // 如果是刚上传的文件，使用 URL.createObjectURL 创建预览地址
    if (file.url) {
      previewUrl.value = file.url
    } else {
      // 如果是已有的图片，直接使用 storeInfo 中的地址
      previewUrl.value = storeInfo[key]
    }
    showViewer.value = true
  }
  // 不能重复命名
  const handleRemove: any = () => {
    storeInfo.logo = ''
  }
  const handleRemoveBus: any = () => {
    storeInfo.business_license = ''
  }
  const getOSSParams = async () => {
    const { data } = await getOSSParam()
    uploadParams.value = data
  }

  const busFilelist = ref([])
  const logoFilelist = ref([])
  const getSupplierInfoData = async () => {
    const { data } = await getSupplierInfo()
    Object.assign(storeInfo, data)
    busFilelist.value = [{ url: data.business_license }]
    logoFilelist.value = [{ url: data.logo }]
    storeInfo.category_ids = data.category_data.map((item) => item.id)
  }
  const cateList = ref([])
  const getCatelistData = async () => {
    const { data } = await getcateList()
    cateList.value = data.data
  }

  onMounted(async () => {
    getOSSParams()
    await getCatelistData()
    await getSupplierInfoData()
  })
</script>
<style scoped></style>

<style lang="scss" scoped>
  .is-error {
    :deep(.el-input__wrapper) {
      border: 1px solid #f56c6c;
      &:focus {
        border: 1px solid #1890ff;
      }
    }
  }
  .store-info-container {
    padding: 20px;

    .store-info-card,
    .audit-result-card {
      margin-bottom: 20px;

      .card-header {
        h3 {
          margin: 0;
          color: #303133;
        }
      }
    }

    .license-image,
    .logo-image {
      width: 200px;
      height: 100px;
      object-fit: contain;
    }

    .button-container {
      text-align: center;
      margin-top: 20px;
    }
  }

  :deep(.el-descriptions__label) {
    width: 120px;
    text-align: right;
    font-weight: bold;
  }
  .set-address {
    cursor: pointer;
    color: #7aa9f7;
    border-bottom: 1px solid #7aa9f7;
  }

  // 添加预览相关样式
  :deep(.el-image-viewer__wrapper) {
    .el-image-viewer__close {
      color: #fff;
    }
  }

  .el-image {
    cursor: pointer;
  }

  :deep(.el-card.is-always-shadow) {
    box-shadow: none !important;
  }
  :deep(.el-card) {
    border: none !important;
  }
</style>
